//
//  AdvertisementController.m
//  Estate
//
//  Created by heyong on 2016/11/28.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "AdvertisementController.h"
#import <JavaScriptCore/JavaScriptCore.h>

@interface AdvertisementController (){
    JSContext *_context;
}
@end

@implementation AdvertisementController

- (UIWebView *)webView{
    if(!_webView){
        _webView=[[UIWebView alloc]initWithFrame:CGRectMake(0, 64, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-64)];
        _webView.backgroundColor=[UIColor clearColor];
        _webView.scalesPageToFit = YES;
    }
    return _webView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *adv=self.davDic[@"advertisementType"];
    if([adv isEqualToString:@"1"]){
        self.title=@"广告";

    }else if ([adv isEqualToString:@"0"]){
        self.title=@"通知";
    }
    self.view.backgroundColor=[UIColor colorWithRed:0.18 green:0.19 blue:0.20 alpha:1.00];
    [self loadLab];
    [self.view addSubview: self.webView];
    self.webView.delegate=self;
    [self loadHtml];
    
}

- (void)oldMethold{
    //    NSString * path = [DEF_SEARCHPATH stringByAppendingString:[NSString stringWithFormat:@"/Caches/%lu.html",(unsigned long)[self.httpUrl hash]]];
    //    NSLog(@"htmlPath:%@",path);
    //    NSFileManager *fileManager = [[NSFileManager alloc]init];
    //    if ([fileManager fileExistsAtPath:path]==YES) {
    //        NSLog(@"已经存在 加载本地");
    //        NSURL *url=[NSURL fileURLWithPath:path];
    //        NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //        [self.webView loadRequest:request];
    //        [self loadHtml];
    
    //        NSString *path = [[NSBundle mainBundle] bundlePath];
    //        NSURL *baseURL = [NSURL fileURLWithPath:path];
    //        NSString * htmlPath = [[NSBundle mainBundle] pathForResource:@"index"
    //                                                              ofType:@"html"];
    //        NSString * htmlCont = [NSString stringWithContentsOfFile:htmlPath
    //                                                        encoding:NSUTF8StringEncoding
    //                                                           error:nil];
    //        [self.webView loadHTMLString:htmlCont baseURL:baseURL];
    //    }else{
    //        [self loadHtml];
    //        [self writeToCache];
    //    }

}

- (void)loadLab{
    UILabel *lab=[[UILabel alloc]initWithFrame:CGRectMake(0, 65, DEF_SCREEN_WIDTH, 30)];
    lab.text=@"网页由www.bjttsx.com提供";
    lab.textAlignment=1;
    lab.font=[UIFont boldSystemFontOfSize:13*BIZ];
    lab.textColor=[UIColor grayColor];
    [self.view addSubview:lab];
}

#pragma mark 加载html
- (void)loadHtml{
    NSString *path = [[NSBundle mainBundle] bundlePath];
    NSURL *baseURL = [NSURL fileURLWithPath:path];
    NSString * htmlPath = [[NSBundle mainBundle] pathForResource:@"index1"
                                                          ofType:@"html"];
    NSString * htmlCont = [NSString stringWithContentsOfFile:htmlPath
                                                    encoding:NSUTF8StringEncoding
                                                       error:nil];
    [self.webView loadHTMLString:htmlCont baseURL:baseURL];
}

#pragma mark-网页缓存 写入文件
- (void)writeToCache
{
    NSString *htmlResponseStr=[NSString stringWithContentsOfURL:[NSURL URLWithString:self.httpUrl] encoding:NSUTF8StringEncoding error:nil];
    //创建文件管理器
    NSFileManager *fileManager = [[NSFileManager alloc]init];
    //获取document路径
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    [fileManager createDirectoryAtPath:[cachesPath stringByAppendingString:@"/Caches"]withIntermediateDirectories:YES attributes:nil error:nil];
    
    //写入路径
    NSString * path = [cachesPath stringByAppendingString:[NSString stringWithFormat:@"/Caches/%lu.html",(unsigned long)[self.httpUrl hash]]];
    
//    NSLog(@"path:%@",path);
    
    bool write=[htmlResponseStr writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
    if(write){
        NSLog(@"写入成功");
    }else{
        NSLog(@"写入失败");
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 *  需要加载完才能调用
 */

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    
    //首先创建JSContext 对象（此处通过当前webView的键获取到jscontext）
    _context=[self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    
    _context.exceptionHandler =
    ^(JSContext *context, JSValue *exceptionValue)
    {
        context.exception = exceptionValue;
        NSLog(@"JS错误:%@", exceptionValue);
    };
    NSString *str=[LSUtility dictionaryToJson_4:self.davDic];
    NSString *strs=[str stringByReplacingOccurrencesOfString:@"\\/" withString:@"/"];
    
//    NSLog(@"strs:%@",strs);
    NSString *proJs=[NSString stringWithFormat:@"setcon(%@)",strs];
    
    [_context evaluateScript:proJs];//通过oc方法调用js的代码
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
